package com.mingyizhudao.app.view.home;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow.OnDismissListener;

import com.dixiang.framework.common.QJNetUICallback;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.widget.LoadingDialog;
import com.dixiang.framework.widget.PullToRefreshView;
import com.dixiang.framework.widget.PullToRefreshView.OnFooterRefreshListener;
import com.dixiang.framework.widget.PullToRefreshView.OnHeaderRefreshListener;
import com.google.gson.reflect.TypeToken;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.entity.AreaEntity;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.utils.IntentHelper;
import com.mingyizhudao.app.view.MYApplication;
import com.mingyizhudao.app.view.MYBaseActivity;
import com.mingyizhudao.app.view.home.adapter.DeptToHospitalAdapter;
import com.mingyizhudao.app.view.home.bean.DeptToHospitalEntity;
import com.mingyizhudao.app.view.home.bean.DisNavsEntity;
import com.mingyizhudao.app.view.recommend.DeptIntroduceActivity;
import com.mingyizhudao.app.view.recommend.adapter.AreaListAdapter;

public class DeptToHospitalActivityTemp2 extends MYBaseActivity{
	private Context context;
	private LayoutInflater mInflater;
	private DisNavsEntity disNavsEntity;
	
	
	private PullToRefreshView refresh_lv_hospital;
	private ListView mActual_lv_hospital;
	private DeptToHospitalAdapter deptHospitalAdapter;
	private List<DeptToHospitalEntity> hospitalList;
	
	
	private int page = 1;
//	private List<ProvinceEntity> listProvince;
//	private  String ProvinceId = "-1";//用来记录选中的省份
	//	private  String cityId = "1";
	//	private  String cityName = "北京";
	
	private List<AreaEntity> areaList;
	private  String areaId = "0";
	private  String areaName = "全部地区";
	
	private String disease_sub_category = "0";
	private String deptName = "科室";
	
	private LinearLayout ll_data_null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dept_to_hospital_temp);
		initView();
	}

	@Override
	public void initHeaderView() {
		setTopViewBg(R.color.actionbar_bg_color);
		initBackView(R.drawable.left_back_white_icon, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		
		initOptionView( R.drawable.area_down_ic, 0, new  OnClickListener() {
			@Override
			public void onClick(View v) {
//				if (listProvince != null && listProvince.size() > 0) {
//					initCityPopupWindow(v, context);
//				} else {
//					Toast.makeText(context, "数据加载未完成！", 0).show();
//				}
				
				if (areaList != null && areaList.size() > 0) {
					initOptionView(R.drawable.area_up_ic);
					initSingleCityPopupWindow(v, context);
				} else {
					Toast.makeText(context, "数据加载未完成！", 0).show();
				}
				
			}
		});
	}



	private void initView() {
		
		context = this;
		mInflater = LayoutInflater.from(context);
		
		disNavsEntity = (DisNavsEntity) getIntent().getSerializableExtra("disNavsEntity");
		ll_data_null = (LinearLayout) findViewById(R.id.ll_data_null);
		refresh_lv_hospital = (PullToRefreshView)findViewById(R.id.refresh_lv_hospital);
		mActual_lv_hospital = (ListView)findViewById(R.id.mActual_lv_hospital);
		
		// 获取头部控件
		View headerView = activity.getLayoutInflater().inflate(R.layout.activity_dept_to_hostital_header, null);
		mActual_lv_hospital.addHeaderView(headerView, false, false);
		
		
		deptName = disNavsEntity.getSubCat().get(0).getName();
		disease_sub_category = "" + disNavsEntity.getSubCat().get(0).getId();
		setTitleViewValue(deptName, R.color.white ,0,null);
		
		setRightText( areaName ,R.color.white);
		
		getHospitalDate(true);
		

		if (deptHospitalAdapter == null || deptHospitalAdapter.isEmpty()) {
			hospitalList = new ArrayList<DeptToHospitalEntity>();
			deptHospitalAdapter = new DeptToHospitalAdapter( context, hospitalList);
		}

//		if(listProvince == null || listProvince.size() == 0)
		
		if(areaList == null || areaList.size() == 0)
			getCityDate();
		mActual_lv_hospital.setAdapter( deptHospitalAdapter );



		refresh_lv_hospital
		.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {

			@Override
			public void onHeaderRefresh(PullToRefreshView refreshView) {
				// 刷新不加载更多
				page = 1;
				getHospitalDate(true);
			}
		});

		refresh_lv_hospital
		.setOnFooterRefreshListener(new OnFooterRefreshListener() {

			@Override
			public void onFooterRefresh(PullToRefreshView refreshView) {
				// 加载更多
				page++;
				getHospitalDate(false);
			}
		});

		mActual_lv_hospital.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if(hospitalList == null) return;
				Bundle bundle = new Bundle();
				DeptToHospitalEntity hospitalEntity = hospitalList.get(position-1);
				
				bundle.putSerializable( "deptUrl", Constants.baseURL + "hospitaldept/"+ hospitalEntity.getHp_dept_id());
					
				bundle.putSerializable("deptId", hospitalEntity.getHp_dept_id());
				bundle.putSerializable("facultyName", hospitalEntity.getHp_dept_name() );
					
				bundle.putSerializable("hospitalName", hospitalEntity.getName());
				
				IntentHelper.getInstance(context).gotoActivity(DeptIntroduceActivity.class, bundle);
			}

		});
		
	}


	public void getHospitalDate(final boolean isFresh) {
		
		String deptIdPram = "";
		if ("0".equals(disease_sub_category)) {
			deptIdPram = "";
		} else {
			deptIdPram = "&disease_sub_category=" + disease_sub_category;
		}
		
//		String cityIdPram = "";
//		if ("-1".equals(cityId)) {
//			cityIdPram = ""  ;
//		}else {
//			cityIdPram = "&city=" + cityId;
//		}
		String url = Constants.baseURL + "hospital_home" + "?page=" + page + deptIdPram + "&area=" + areaId;

		LoadingDialog.getInstance(activity).show();
		
		getHttpResult(url, Constants.HTTP_INDEX.First, new TypeToken<QjResult<List<DeptToHospitalEntity>>>() {});
	}
	
	private void getCityDate() {
		//String url = Constants.baseURL + "city?type=hospital&has_team=0"; //+ Constants.basePARAM;//+ "&api=4"
		String url = Constants.baseURL + "area"; 
		getHttpResult(url, Constants.HTTP_INDEX.Second, new TypeToken<QjResult<List<AreaEntity>>>() {});
	}

	
	@Override
	public void onSuccess(QjResult result, String flg) {
		super.onSuccess(result, flg);
		if(flg.equals(Constants.HTTP_INDEX.First)){
			List<DeptToHospitalEntity> list = (List<DeptToHospitalEntity>) result.getResults();
			if (list == null|| (list != null && list.size() <= 0)) {
				Toast.makeText(context, "没有更多数据！", 0).show();
				if (page == 1) {
					if(hospitalList != null) hospitalList.clear();
					
					ll_data_null.setVisibility(View.VISIBLE);
					deptHospitalAdapter.notifyDataSetChanged();
				}
			} else {
				ll_data_null.setVisibility(View.GONE);
				if (page == 1) {
					hospitalList.clear();
				}
				hospitalList.addAll(list);
				deptHospitalAdapter.notifyDataSetChanged();
			}
		}else if(flg.equals(Constants.HTTP_INDEX.Second)){
//			listProvince = (List<ProvinceEntity>) result.getResults();
//			
//			ProvinceEntity provinceEntity= new ProvinceEntity();
//			provinceEntity.setId(-1);
//			provinceEntity.setState("全部");
//			provinceEntity.setSubCity(new ArrayList<CityEntity>());
//			listProvince.add(0,provinceEntity);
			
			areaList = (List<AreaEntity>) result.getResults();
		}
	}
	
	@Override
	public void onCompleted(Exception e, String flg) {
		super.onCompleted(e, flg);
		if(flg.equals(Constants.HTTP_INDEX.First)){
			handler.post(new Runnable() {
				
				@Override
				public void run() {
					refresh_lv_hospital.onHeaderRefreshComplete();
					refresh_lv_hospital.onFooterRefreshComplete();
				}
			});
			LoadingDialog.getInstance(activity).dismiss();
		}
	}
	
	
	private void initSingleCityPopupWindow(View v, Context context) {

		// 设置pop窗口的视图，用布局转换器将xml转换成view
		View contentView = mInflater.inflate(R.layout.pop_dept, null);
		// 获得pop窗口，设置大小(宽高设置为填充)，ViewGroup.LayoutParams.MATCH_PARENT填充父类
		final PopupWindow pop = new PopupWindow(
				contentView,
				LayoutParams.MATCH_PARENT,
				(int) (MYApplication.heightPixels - (MYApplication.startheight + ((43) * MYApplication.density))));
		
		ListView lv_city = (ListView) contentView.findViewById(R.id.lv_dept);

		AreaListAdapter cityListAdapter = new AreaListAdapter(context, areaList);
		cityListAdapter.setSelected(areaId);
		lv_city.setAdapter(cityListAdapter);
		
		if (areaList.size()>0) {
			for (int i = 0; i < areaList.size(); i++) {
				if (areaId.equals(""+areaList.get(i).getArea_id())) {
					lv_city.setSelection(i);
					break;
				}
			}
		}
		
		lv_city.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				
				page = 1;
				areaName = areaList.get(position).getArea_name();

				setRightText( areaName ,R.color.white);
				areaId = "" + areaList.get(position).getArea_id();
				getHospitalDate(true);
				if (pop.isShowing()) {
					pop.dismiss();
				}
			}

		});
		

		// 获得焦点
		pop.setFocusable(true);
		pop.setBackgroundDrawable(new BitmapDrawable());// 点击完按钮后另其消失（方法：设置一个空的bitmap）
		// 设置pop窗口显示的位置
		// 将按钮和pop窗口关联上，v表示一个显示的基点(按钮的基点为左下点)
		pop.showAtLocation(
				v,
				Gravity.TOP,
				0,
				(int) (MYApplication.startheight + (43 * MYApplication.density)));
		pop.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				initOptionView(R.drawable.area_down_ic);
			}
		});

	}
	

}
